/*
 * @Author: yangzonglong
 * @Date: 2021-09-21 15:33:58
 * @version: v1.0.0
 * @Descripttion: 工厂库位联动
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-09-26 14:17:51
 * @Auditor:
 */
import React, { memo, useState, useEffect } from 'react';
import { Cascader } from 'antd';
import { getPlantLocation } from './api';

export type PlanLocationProps = {
  value: string;
  label: string;
  children: Array<{ label: string; value: string; binFlag?: boolean }>;
};

interface IProps {
  value: string[];
  onChange(data: string[], name: string[], binFlag: boolean): void;
  size?: 'large' | 'middle' | 'small';
  style?: React.CSSProperties
}

export default memo(({ value, onChange, size, style }: IProps) => {
  const [options, setOptions] = useState<PlanLocationProps[]>([]);

  useEffect(() => {
    let activity = true;
    getPlantLocation((result: PlanLocationProps[]) => {
      if (result && activity) setOptions(result);
    });

    return () => {
      activity = false;
    };
  }, []);

  return (
    <Cascader
      placeholder={window.$app.t('plsStorageLocation')}
      options={options}
      value={value.some(item => !item) ? [] : value}
      expandTrigger="hover"
      size={size || 'middle'}
      style={style}
      onChange={(v) => {
        let _plant = options.filter((item) => item.value === v[0]);
        let _stoLocation = _plant[0]['children'].filter((item) => item.value === v[1]);

        onChange(v as string[], [_plant[0]['label'], _stoLocation[0]['label']], _stoLocation[0].binFlag || false);
      }}
    />
  );
});
